package com.mgg.user.controller.user;

import com.mgg.common.entity.ValidateCode;
import com.mgg.common.enums.UserRoleEnum;
import com.mgg.common.messaging.UserRegisterProcessor;
import com.mgg.common.payload.UserRegisterPayload;
import com.mgg.common.util.DateUtils;
import com.mgg.common.util.ResultVOUtil;
import com.mgg.common.util.ValidateCodeUtils;
import com.mgg.common.entity.UserDO;
import com.mgg.user.enums.UserResultEnum;
import com.mgg.user.service.BaseUserService;
import com.mgg.user.service.shop.ShopService;
import com.mgg.user.service.user.UserSalaryService;
import com.mgg.user.service.user.UserService;
import com.mgg.common.vo.AccountVO;
import com.mgg.user.vo.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.web.PageableDefault;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private BaseUserService baseUserService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private UserSalaryService userSalaryService;

    @Autowired
    private UserRegisterProcessor userRegisterProcessor;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 手机号码注册
     * @param mobile
     * @param smsCode
     * @param inviteCode
     * @param realName
     * @return
     * @throws Exception
     */
    @PostMapping("/register/mobile")
    public Object register(@RequestParam String mobile, @RequestParam String smsCode, @RequestParam String inviteCode, @RequestParam( required = false) String realName){
        ValidateCode validateCode = (ValidateCode) redisTemplate.opsForValue().get("code:sms:" + mobile);
        ValidateCodeUtils.checkCode(smsCode,validateCode);
        UserDO inviteUser = baseUserService.getUserByShopCode(inviteCode);
        if (inviteUser == null) {
            return ResultVOUtil.error(UserResultEnum.SHOP_CODE_ERROR);
        }
        UserDO user = baseUserService.getUserByPhone(mobile);
        if (user != null) {
            Map<String,String> resultMap = new HashMap<>();
            resultMap.put("msg", "手机号码已注册");
            return ResultVOUtil.success(resultMap);
        }

        // 新用户，创建用户信息
        userService.saveVipUser(mobile, inviteCode, realName, inviteUser.getUserId());
        user = baseUserService.getUserByPhone(mobile);
        if (user == null) {
            return ResultVOUtil.error(UserResultEnum.RIGIST_FAIL);
        }
        //发送用户VIP注册消息
        UserRegisterPayload payload = new UserRegisterPayload();
        payload.setUserId(user.getUserId());
//		payload.setRefereeId(inviteUser.getUserId());
        Message<UserRegisterPayload> message = MessageBuilder.withPayload(payload).build();
        userRegisterProcessor.output().send(message);
        return ResultVOUtil.success();
    }

    /**
     * userId查询用户信息
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value="/query/byid/{userId}")
    public Object findUserById(@PathVariable("userId") String userId) {
        if (StringUtils.isEmpty(userId)) {
            return ResultVOUtil.error(UserResultEnum.USER_QEURY_CONDITION_ERROR);
        }
        UserInfoVO userInfoVO = userService.getUserInfoByUserId(userId);
        return ResultVOUtil.success(userInfoVO);
    }

    /**
     * userId查询用户信息
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value="/bywx")
    public Object findAppUserById(@RequestParam("userId") String userId) throws Exception {
        if (StringUtils.isEmpty(userId)) {
            return ResultVOUtil.error(UserResultEnum.USER_QEURY_CONDITION_ERROR);
        }
        UserInfoVO userInfoVO = userService.getAppUserById(userId);
        return ResultVOUtil.success(userInfoVO);
    }

    /**
     * 我的首页信息
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value="/index/info")
    public Object getUserIndexInfo(@RequestHeader("user_id") String userId) {

        Map<String, Object> result = new HashMap<>();

        AccountVO account = baseUserService.getUserAccountByUserId(userId);
        //美币
        result.put("coin", userService.getUserMCoin(userId));
        //优惠券
        result.put("coupon", userService.getUserCoupon(userId));
        //余额
        result.put("amount", account.getAmount());

        UserInfoVO user = userService.getUserInfoByUserId(userId);

        //获取上级信息
        UserDO tutor = baseUserService.getSuperUserByUserId(userId);
        Map<String,Object> tutorMap = new HashMap<>();
        if (tutor != null) {
            tutorMap.put("name", tutor.getUsername() + "（" + tutor.getRealName() +"）");
            tutorMap.put("shopCode", tutor.getShopCode());
        }

        result.put("tutor", tutorMap);
        result.put("user", user);
        String roleCode = user.getRoleCode();

        if ((UserRoleEnum.TUTOR.getCode().equals(roleCode) || UserRoleEnum.MANAGER.getCode().equals(roleCode)
                || UserRoleEnum.DIRECTOR.getCode().equals(roleCode) )) {
            String shopCode = user.getShopCode();
            //本月销售额，今日访问量，今日订单数，会员人数
            Map<String,Object> shopCount = new HashMap<>();
            shopCount.put("monthSalesAmount", shopService.getMonthSalesAmount(shopCode));
            shopCount.put("todayViewNum", shopService.getTodayVisitNum(shopCode));
            shopCount.put("todayOrderNum", shopService.getTodayOrderNum(shopCode));
            shopCount.put("memberNum", shopService.countMemberNum(shopCode));
            result.put("shopInfo", shopCount);

            //累计收益，代收收益，今日收益， 本月收益
            Map<String,Object> incomeCount = new HashMap<>();
            incomeCount.put("totalIncome", account.getTotalIncome());
            incomeCount.put("monthIncome", shopService.getMonthIncome(userId));
            incomeCount.put("todayIncome", shopService.getTodayIncome(userId));
            incomeCount.put("preIncome", account.getPreAmount());
            result.put("accountInfo", incomeCount);
        }
        return ResultVOUtil.success(result);
    }

    /**
     * 我的培训老师
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value="/teachers")
    public Object myTrainingTeacher(@RequestHeader("user_id") String userId) {
        List<Map<String,String>> superlist = new ArrayList<>();
        UserDO superUser = baseUserService.getSuperUserByUserId(userId);
        if (superUser != null) {
            superlist.add(getUserMap(superUser));
            UserDO ssuperUser = baseUserService.getSuperUserByUserId(userId);
            if (ssuperUser != null) {
                superlist.add(getUserMap(ssuperUser));
            }
        }
        return ResultVOUtil.success(superlist);
    }

    private Map<String,String> getUserMap(UserDO user) {
        Map<String,String> userMap = new HashMap<>();
        userMap.put("username", user.getUsername());
        userMap.put("real_name", user.getRealName());
        userMap.put("role_name", user.getRealName());
        userMap.put("role_code", user.getRoleCode());
        return userMap;
    }

    /**
     * 培训绩效统计
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value="/salary")
    public Object userSalaryInfo(@RequestHeader("user_id") String userId) {
        //本月工资统计
        LocalDate date = LocalDate.now();
        Map<String,Object> thisMonthCount = userSalaryService.countSalaryByMonth(userId, DateUtils.getMonth(date));

        //上2个月的工资统计
        Map<String,Object> lastMonthCount = userSalaryService.countSalaryByMonth(userId,DateUtils.getMonth(date.minusMonths(1)));
        Map<String,Object> beforeLastMonthCount = userSalaryService.countSalaryByMonth(userId,DateUtils.getMonth(date.minusMonths(2)));

        Map<String,Object> result = new HashMap<>();
        result.put("thisMonthCount", thisMonthCount);
        result.put("lastMonthCount", lastMonthCount);
        result.put("beforeLastMonthCount", beforeLastMonthCount);
        return ResultVOUtil.success(result);
    }

    /**
     * 工资明细
     * @param userId
     * @return
     * @throws Exception
     */
    @GetMapping(value="/salary/details")
    public Object userSalaryDetails(@RequestHeader("user_id") String userId, @RequestParam("type") String type, @RequestParam("month") String month, @PageableDefault(page = 1, size = 20) Pageable page ) {
        List<Map<String,Object>> salaryList = userSalaryService.listSalaryDetailsByMonth(userId,month,type,page);
        return ResultVOUtil.success(salaryList);
    }

    /**
     *
     * @param userId
     * @return
     */
    @GetMapping(value="/baseInfo")
    public UserDO getUserByUserId(@RequestParam("user_id") String userId) {
        UserDO user = baseUserService.getUserByUserId(userId);
        return user;
    }
}
